# -*- coding: utf-8 -*-

import csv
import os, sys
import zipfile
import win32api, win32con
import shutil
import time
from time import sleep
from pywinauto.application import Application
from extendScript.GenerationHTMLReport import GenerationReport
from extendScript.GetProcessInfo import getProcessInfo
from extendScript.RWExcleIMPL import ExcelImpl

import win32api, win32con, SendKeys

reload(sys)
sys.setdefaultencoding("utf-8")


class CalcPxy:
    def __init__(self, staticBut, tagNum, tagNum2=None):
        self.staticBut = staticBut
        self.tagX = (staticBut.Rectangle().right - staticBut.Rectangle().left) / 2 + staticBut.Rectangle().left     #获取控件的中心点x的值
        #self.tagY = (staticBut.Rectangle().bottom - staticBut.Rectangle().top) / 2 + staticBut.Rectangle().top     #获取控件的中心点y的值(x,y)为控件的中心点
        self.tagY = (
                    staticBut.Rectangle().bottom - staticBut.Rectangle().top) / 2 + staticBut.Rectangle().top + 40 + 30 * (
        tagNum - 1) + 15
        if tagNum2 is not None:
            self.tagX1 = (
                         staticBut.Rectangle().right - staticBut.Rectangle().left) / 2 + staticBut.Rectangle().left + 70
            self.tagY1 = (
                         staticBut.Rectangle().bottom - staticBut.Rectangle().top) / 2 + staticBut.Rectangle().top + 40 + 30 * (
            tagNum - 1) + 15 + 30 * (tagNum2 - 1)

    def level1_but_click(self):     #设置鼠标移动到控件中心左键单击鼠标
        # print self.tagX,self.tagY
        win32api.SetCursorPos((self.tagX, self.tagY))
        sleep(1)
        self.staticBut.DragMouse()
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

    def level2_but_click(self):     #设置鼠标移动到控件中心左键单击鼠标
        # print self.tagX1,self.tagY1
        win32api.SetCursorPos((self.tagX1, self.tagY1))
        sleep(1)
        # self.staticBut.DragMouse()
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)


class setValueToGUI():
    def __init__(self, listValue=None):
        self.ei = ExcelImpl()
        self.listValue = self.ei.getOneTestCaseByExcel(type='DeuGlobeExplorer', testNo=listValue)
        self.startDeuGlobeExplorer(self.listValue)

    def startDeuGlobeExplorer(self, data):
        self.data = data

        filePath = self.ei.getFilePath(type='DeuGlobeExplorer')

        self.app = Application().start(filePath)    #启动程序
        starttime1 = time.strftime("%Y-%m-%d %X", time.localtime())     #获取当前时间
        # print starttime1

        self.wfMain = self.app.DeuGlobeExplorer     #连接程序
        self.wfMain.Wait('ready')

        # 01
        menandcpu = getProcessInfo("DeuGlobeExplorer.exe", 8, 1)    #调用getProcessInfo

        # 02
        menandcpu.start()

        # 03
        if data[1] == u"本地加载":
            self.createDeuFile()    #调用createDeuFile
            if data[2] == u"是":
                datalist = self.loaddata(data[3])

                if len(datalist[1]) != 0:   #判断列表内容
                    # self.loadDOM(data[3] + "\\" + " ".join(str('"' + j + '"') for j in datalist[1]))
                    # print datalist[1]
                    for j in range(len(datalist[1])):   #循环取列表里的值
                        self.loadDOM(data[3] + "\\" + datalist[1][j])
                        sleep(1)

                if len(datalist[2]) != 0:
                    # self.loadDEM(data[3])
                    for k in range(len(datalist[2])):
                        self.loadDEM(data[3] + "\\" + datalist[2][k])
                        sleep(1)

                # listmodname = ""
                # for p in datalist[0]:
                #     listmodname = listmodname + p.decode("utf-8") + " "

                if len(datalist[0]) != 0:
                    self.loadMOD(data[3])
                # self.loadMOD(data[3], u" ".join(str('"' + l + '"') for l in datalist[0]))
            else:
                self.goto()
                sleep(1)
                self.app[u'WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'地形数据'].click()
                sleep(1)
                self.app[u'WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'模型数据'].Click()
                sleep(1)
                self.goto()
            if data[4] == u"是":
                self.loadROAM(data[5])
        else:
            self.createDeuFile()
            self.goto()
            sleep(1)
            self.app[u'WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'地形数据'].click()
            sleep(1)
            self.app[u'WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'模型数据'].Click()
            sleep(1)
            self.goto()
            if data[4] == u"是":
                self.loadROAM(data[5])

        menandcpu.stop()
        menandcpu.join()
        # self.wfMain["STATIC56"].Click()
        # self.app["FormMyMessageBox"]["STATIC2"].Click()
        self.wfMain.Close(8)    #8秒关闭程序等待
        endtime1 = time.strftime("%Y-%m-%d %X", time.localtime())   #获取当前时间
        # endtime1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # print endtime1

        zip_file = data[0] + '_OutPic.zip'
        self.compress(zip_file, os.path.join(os.getcwd(), os.getcwd() + u'\\outputdata\\OutPic\\'))
        if os.path.exists(os.getcwd() + u'\\outputdata\\DataSet\\'+ zip_file):  #判断文件是否存在，存在就删掉
            os.remove(os.getcwd() + u'\\outputdata\\DataSet\\'+ zip_file)
            shutil.move(os.getcwd() + "\\" + zip_file, os.getcwd() + u'\\outputdata\\DataSet\\')    #移动文件位置
        else:
            shutil.move(os.getcwd() + "\\" + zip_file, os.getcwd() + u'\\outputdata\\DataSet\\')

        aa = initThisTester().Cpu_and_Mem()
        # print self.starttime,self.endtime
        if data[4] == u'是':
            datasj = [[self.starttime, self.endtime], aa[0], aa[1], aa[2]]
            # print datasj
            cc = GenerationReport(data[0] + '_' + u'DeuGlobeExplorer自动化测试报告', u'自动化测试报告', u'测试用例' + data[0], datasj)
            cc.generation_report()
        else:
            datasj = [[starttime1, endtime1], aa[0], aa[1], aa[2]]
            # print datasj
            # print time.strftime("%Y-%m-%d %X", time.localtime())
            cc = GenerationReport(data[0] + '_' + u'DeuGlobeExplorer自动化测试报告', u'自动化测试报告', u'测试用例' + data[0], datasj)
            cc.generation_report()

    def createDeuFile(self):
        i = self.listValue
        CalcPxy(self.wfMain["Static62"], 1).level1_but_click()  # 打开新建查窗口
        cachepah = self.ei.getFilePath(type="Cachepah")

        if i[1] == u'本地加载':
            ipaddress = self.ei.getFilePath(type="Localhost")
        else:
            ipaddress = self.ei.getFilePath(type="HostIP")

        apacheport = self.ei.getFilePath(type="HostPort")
        ThreadCount = self.ei.getFilePath(type="FetchingThreadCount")
        AntiAlias = self.ei.getFilePath(type="BifurcateFetchingThread")
        bifurcateThread = self.ei.getFilePath(type="AntiAliasTimes")
        permissionip = self.ei.getFilePath(type="QueryIP")
        permissionport = self.ei.getFilePath(type="QueryPort")
        username = self.ei.getFilePath(type="user")
        userpassword = self.ei.getFilePath(type="password")

        wfMain_newConn = self.app[u'WindowsForms10.Window.8.app.0.2bf8098_r25_ad1']  # 连接新建窗口
        sleep(0.1)
        wfMain_newConn['EDIT3'].SetEditText(cachepah)  # 本地缓存文本框    SetEditText()清空文本内容再进行输入内容
        wfMain_newConn['EDIT4'].SetEditText(ipaddress)  # 服务器地址文本框
        wfMain_newConn['EDIT2'].SetEditText(apacheport)  # 服务器端口文本框
        wfMain_newConn['EDIT5'].SetEditText(ThreadCount)  # 数据线程数文本框
        # wfMain_newConn['COMBOBOX'].Select(0)  # 反走样下拉列表
        if AntiAlias == 0:
            wfMain_newConn['COMBOBOX'].Select(0)    #选择下列框的第一个选项
        if AntiAlias == 2:
            wfMain_newConn['COMBOBOX'].Select(1)
        if AntiAlias == 4:
            wfMain_newConn['COMBOBOX'].Select(2)
        if AntiAlias == 8:
            wfMain_newConn['COMBOBOX'].Select(3)
        if AntiAlias == 16:
            wfMain_newConn['COMBOBOX'].Select(4)
        if AntiAlias == 32:
            wfMain_newConn['COMBOBOX'].Select(5)

        if bifurcateThread == 1:
            wfMain_newConn[u'启用'].Click()  # 勾选启用分叉线程复选框
        else:
            sleep(0.5)
        wfMain_newConn[u'确定'].Click()  # 点击确定
        sleep(1)

        savefrom = self.app[u'另存为']  # 连接另存为窗口
        if i[1] == u'本地加载':
            inputpath = os.getcwd() + u"\\outputdata\\DataSet\\" + i[0] + "_" + i[1]    # os.getcwd()工作目录
        else:
            inputpath = os.getcwd() + u"\\outputdata\\DataSet\\" + i[0] + "_" + i[1]

        savefrom[u'Edit'].SetEditText(inputpath)
        sleep(0.5)

        savefrom[u'保存(S)'].Click()
        try:
            savefrom[u'保存(S)'].Click()
        except Exception as e:
            pass

        self.samename()

        # 登录
        loginfrom = self.app['WindowsForms10.Window.8.app.0.2bf8098_r25_ad1']  # 连接登录窗口
        if i[1] == u'本地加载':
            loginfrom[u'取消'].Click()
            sleep(1)
        else:
            loginfrom['EDIT1'].SetEditText(permissionip)  # 权限服务器地址
            loginfrom['EDIT2'].SetEditText(permissionport)  # 权限服务端口
            loginfrom['EDIT4'].SetEditText(username)  # 用户名
            loginfrom['EDIT3'].SetEditText(userpassword)  # 密码
            sleep(0.5)
            loginfrom[u'确定'].Click()

    def loadDOM(self, datapath):
        # self.app['WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'影像数据'].click()
        # sleep(0.5)

        self.wfMain[u'导入51'].Click()
        wfMain_open = self.app[u'打开']  # 连接打开窗口

        wfMain_open[u'Edit'].SetEditText(datapath)
        sleep(0.5)

        wfMain_open[u'打开(&O)'].Click()
        try:
            wfMain_open[u'打开(&O)'].Click()
        except:
            pass

        # datalistwf = wfMain_open[u"DirectUIHWND2"]
        # (x, y) = ((datalistwf.Rectangle().right - datalistwf.Rectangle().left) / 2 + datalistwf.Rectangle().left,
        #           (datalistwf.Rectangle().bottom - datalistwf.Rectangle().top) / 2 + datalistwf.Rectangle().top)
        #
        # win32api.SetCursorPos((x, datalistwf.Rectangle().top + 40))
        #
        # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
        #
        # SendKeys.SendKeys("^a")   #操作键盘Ctrl+a

        # wfMain_open[u'打开(&O)'].Click()

        # 勾选转到，截图
        self.goto()

    def loadDEM(self, datapath):  # 加载地形数据
        self.app[u'WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'地形数据'].click()
        sleep(0.5)
        self.wfMain[u'导入53'].Click()
        wfMain_open = self.app[u'打开']  # 连接打开窗口

        wfMain_open[u'Edit'].SetEditText(datapath)

        sleep(0.5)

        wfMain_open[u'打开(&O)'].Click()
        try:
            wfMain_open[u'打开(&O)'].Click()
        except:
            pass

        # datalistwf = wfMain_open[u"DirectUIHWND2"]
        # (x, y) = ((datalistwf.Rectangle().right - datalistwf.Rectangle().left) / 2 + datalistwf.Rectangle().left,
        #           (datalistwf.Rectangle().bottom - datalistwf.Rectangle().top) / 2 + datalistwf.Rectangle().top)
        #
        # win32api.SetCursorPos((x, datalistwf.Rectangle().top + 40))
        # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
        #
        # SendKeys.SendKeys("^a")     #操作键盘Ctrl+a
        #
        # wfMain_open[u'打开(&O)'].Click()

        # 勾选转到
        self.goto()

    def loadMOD(self, datapath):
        self.app['WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'模型数据'].Click()
        sleep(0.5)
        self.wfMain[u'导入'].Click()
        wfMain_open = self.app[u'打开']  # 连接打开窗口
        wfMain_open[u'Edit'].SetEditText(datapath)

        sleep(0.5)

        wfMain_open[u'打开(&O)'].Click()
        try:
            wfMain_open[u'打开(&O)'].Click()
        except:
            pass

        datalistwf = wfMain_open[u"DirectUIHWND2"]
        (x, y) = ((datalistwf.Rectangle().right - datalistwf.Rectangle().left) / 2 + datalistwf.Rectangle().left,
                  (datalistwf.Rectangle().bottom - datalistwf.Rectangle().top) / 2 + datalistwf.Rectangle().top)

        win32api.SetCursorPos((x, datalistwf.Rectangle().top + 40))

        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

        SendKeys.SendKeys("^a")

        try:
            wfMain_open[u'打开(&O)'].Click()
        except Exception as e:
            print e

        sleep(5)

        self.goto()

    def loadROAM(self, flypath):
        self.app['WindowsForms10.Window.8.app.0.2bf8098_r25_ad1'][u'路径漫游'].Click()
        sleep(0.5)
        self.wfMain['STATIC63'].Click()

        wfMain_open = self.app[u'打开']  # 连接打开窗口

        wfMain_open[u'Edit'].SetEditText(flypath)

        sleep(0.5)

        wfMain_open[u'打开(&O)'].Click()
        try:
            wfMain_open[u'打开(&O)'].Click()
        except:
            pass

        self.wfMain['STATIC53'].Click()
        self.starttime = time.strftime("%Y-%m-%d %X", time.localtime()) #获取当前时间

        self.wfMain.TypeKeys("{F11}")   #操作键盘按下F11

        sleep(int(self.listValue[6]))

        self.endtime = time.strftime("%Y-%m-%d %X", time.localtime())   #获取当前时间
        # print self.endtime
        self.wfMain.TypeKeys("{F11}")   #操作键盘按下F11

    def loaddata(self, filedirprant):
        data = os.listdir(filedirprant)     #列出文件夹里的文件，生成列表
        listdscfg = []
        listdeudom = []
        listdeudem = []
        for filedir in data:    #将对应格式的文件放到对应的列表
            if filedir.split(".")[1].lower() == "deudom":   #以"."分割字符串
                listyx = filedir.split(".")[0] + '.' + filedir.split(".")[1]
                listdeudom.append(listyx)   #将将对应格式的文件加到列表listdeudom里
            elif filedir.split(".")[1].lower() == "deudem":
                listdx = filedir.split(".")[0] + '.' + filedir.split(".")[1]
                listdeudem.append(listdx)
            elif filedir.split(".")[1] == "dscfg":
                listmx = filedir.split(".")[0] + '.' + filedir.split(".")[1]
                listdscfg.append(listmx)
        return [listdscfg, listdeudom, listdeudem]  #返回三个分类好的内嵌列表

    def samename(self):  # 重名替换
        try:
            comfiresave = self.app[u"确认另存为"]  # 连接确认另存为窗口
            comfiresave[u'是(&Y)'].Click()
            sleep(0.5)
        except:
            sleep(0.1)

    def goto(self):
        i = self.listValue
        root = self.wfMain[U'SysTreeView32'].Root()     #获取树结构的第一级
        qq = root.Children()    #获取树结构的第二级生成列表
        if i[2] == u'否':
            if root.Text() == u'逻辑图层':  #第一级的结构名
                for m in range(0, len(qq)):
                    # print(qq[m].Text())
                    cc = qq[m].Children()   #获取树结构的第三级生成列表
                    for n in range(0, len(cc)):
                        # print (cc[n].Text())
                        cc[n].Click(where="check")  #勾选第三级的第n个结构复选框
                        cc[n].Click(button="left", double=True)     #双击第三级的第n个结构
                        sleep(8)

                        #以下步骤循环四次
                        # for jj in range(4):
                        jj = 0
                        while jj < 4:
                            jj = jj + 1
                            self.wfMain["Static14"].Click()
                            sleep(1)

                        # 截图
                        self.wfMain['Static12'].Click()
                        wfMain_open = self.app[u'另存为']  # 连接打开窗口
                        filepath = os.getcwd() + "\\outputdata\\OutPic\\" + i[0] + "_" + cc[n].Text()
                        wfMain_open[u'Edit'].SetEditText(filepath)
                        sleep(0.5)
                        wfMain_open[u'保存(&O)'].Click()
                        wfMain_open[u'保存(&O)'].Click()
                        self.samename()
            else:
                for m in range(0, len(qq)):
                    # print(qq[m].Text())
                    root.GetChild(qq[m].Text()).Click(button=u'left', double=True)  #获取第二级的第m个节点并且双击左键
                    sleep(28)

                    kk = 0
                    while kk < 3:
                        kk = kk + 1
                        self.wfMain["Static14"].Click()
                        sleep(1)

                    # 截图
                    self.wfMain['Static12'].Click()
                    wfMain_open = self.app[u'另存为']  # 连接打开窗口
                    filepath = os.getcwd() + "\\outputdata\\OutPic\\" + i[0] + "_" + qq[m].Text()
                    wfMain_open[u'Edit'].SetEditText(filepath)
                    sleep(0.5)
                    wfMain_open[u'保存(&O)'].Click()
                    wfMain_open[u'保存(&O)'].Click()
                    self.samename()
        else:
            if root.Text() == u'逻辑图层':
                for m in range(0, len(qq)):
                    # print(qq[m].Text())
                    cc = qq[m].Children()
                    for n in range(0, len(cc)):
                        # print (cc[n].Text())
                        cc[n].Click(where="check")
                        # cc[n].Click(button="left", double=True)
                        # else:
                        #     for m in range(0, len(qq)):
                        #         # print(qq[m].Text())
                        #         # root.GetChild(qq[m].Text()).Click(where="check")
                        #         root.GetChild(qq[m].Text()).Click(button=u'left', double=True)
                        #         sleep(2)

    def compress(self, zip_file, input_dir):    #压缩目录为zip文件
        f_zip = zipfile.ZipFile(zip_file, 'w')
        for root, dirs, files in os.walk(input_dir):
            for f in files:
                abs_path = os.path.join(os.path.join(root, f))
                rel_path = os.path.relpath(abs_path, os.path.dirname(input_dir))
                f_zip.write(abs_path, rel_path, zipfile.ZIP_STORED)

class initThisTester:
    def __init__(self):
        pass

    def delReportAndOutdata(self):
        print u"测试环境初始化，请稍后！"
        self.delReport()
        self.delOutdata()

    def delReport(self):
        # print u"1...报告文件删除中，请稍后！"
        self.delAllfolder(os.getcwd() + "\\ReportFile")
        # print u"1...删除完成..."

    def delOutdata(self):
        # print u"2...输出数据删除中"
        self.delAllfolder(os.getcwd() + "\\outputdata\\DataSet")
        # print u"2...删除完成..."

    def delPicExcel(self):
        self.delAllfolder(os.getcwd() + "\\outputdata\\OutPic")
        self.delAllfolder(os.getcwd() + "\\outputdata\\OutExcel")

    def delAllfolder(self, filepath):
        for dfile in os.listdir(filepath):      #删除文件夹内的所有内容
            os.remove(filepath + "\\" + dfile)

    def Cpu_and_Mem(self, Mincpu=None, Maxcpu=None, Minmem=None, Maxmem=None, Avgmem=None, Minfps=None, Maxfps=None,
                    Avgfps=None):
        filepath = os.getcwd() + '\\' + u'outputdata\\OutExcel'
        data = os.listdir(filepath)     #获取文件夹内的文件，生成列表
        for filedir in data:
            csvfile = open(filepath + "\\" + filedir, "rb") #打开csv文件
            if filedir.split('.')[1] == 'exe_CpuInfo':
                cpulist = []
                aa = csv.reader(csvfile)    #读取csv文件
                for row in aa:
                    # print row[0].decode("utf-8-sig")
                    # print row[1].decode("utf-8-sig")
                    cpulist.append(float(row[1].decode("utf-8-sig")[:-1]))  #取出第一列的内容除去最后一个字符放进cpulist列表
                cpulist.sort()  #将cpulist列表的内容进行排序
                # print cpulist
                Mincpu = str(cpulist[0]) + "%"  #取第一个值
                Maxcpu = str(cpulist[-1]) + "%" #取倒数第一个值
                # print Mincpu, Maxcpu

            elif filedir.split('.')[1] == 'exe_MenInfo':
                memlist = []
                bb = csv.reader(csvfile)
                for row in bb:
                    memlist.append(int(row[1]))
                memlist.sort()
                # print memlist
                sum = 0
                for i in memlist:
                    sum = sum + i
                Minmem = str(memlist[0])
                Maxmem = str(memlist[-1])
                Avgmem = str(sum / len(memlist))
                # print Minmem, Maxmem, Avgmem
            elif filedir[-13:] == "minmaxavg.csv":
                cc = csv.reader(csvfile)
                for row in cc:
                    pass
                Minfps = str(int(row[2]))
                aa = int(row[3])
                if aa >= 60:
                    aa = 60
                Maxfps = str(aa)
                Avgfps = str(int(float(row[4])))
        return [[u"内存", Minmem, Maxmem, Avgmem], [u"CPU", Mincpu, Maxcpu, ""], [u"帧率", Minfps, Maxfps, Avgfps]]

    def jltest_deuglobe(self):
        inittter = initThisTester()

        ei = ExcelImpl()
        listcase = ei.getTestCaseByExcel(type="DeuGlobeExplorer")
        for i in listcase:
            setValueToGUI(i[0])
            inittter.delPicExcel()

if __name__ == '__main__':
    inittter = initThisTester()
    inittter.delReportAndOutdata()

    ei = ExcelImpl()
    listcase = ei.getTestCaseByExcel(type="DeuGlobeExplorer")
    for i in listcase:
        setValueToGUI(i[0])
        inittter.delPicExcel()
